package com.szpx.controller.HZJController;

import com.github.pagehelper.PageInfo;
import com.szpx.entity.HZJ.Announcement;
import com.szpx.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@RestController
@RequestMapping("/api/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 获取公告列表（分页+条件查询）
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param params 查询参数 (例如: title, status)
     * @return 分页结果
     */
    @GetMapping
    public ResponseEntity<PageInfo<Announcement>> getAnnouncements(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam Map<String, Object> params) {
        PageInfo<Announcement> pageInfo = announcementService.getAnnouncementsByPage(pageNum, pageSize, params);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     * 根据ID获取单个公告详情
     * @param id 公告ID
     * @return 公告实体
     */
    @GetMapping("/{id}")
    public ResponseEntity<Announcement> getAnnouncementById(@PathVariable Long id) {
        Announcement announcement = announcementService.getAnnouncementById(id);
        if (announcement != null) {
            return ResponseEntity.ok(announcement);
        }
        return ResponseEntity.notFound().build();
    }

    /**
     * 新增公告
     * @param announcement 公告实体
     * @return 创建后的公告实体
     */
    @PostMapping
    public ResponseEntity<Announcement> createAnnouncement(@RequestBody Announcement announcement) {
        boolean success = announcementService.createAnnouncement(announcement);
        if (success) {
            // 成功后返回带ID的实体
            return ResponseEntity.ok(announcement);
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 更新公告
     * @param id 公告ID
     * @param announcement 公告实体
     * @return 更新后的公告实体
     */
    @PutMapping("/{id}")
    public ResponseEntity<Announcement> updateAnnouncement(@PathVariable Long id, @RequestBody Announcement announcement) {
        announcement.setId(id); // 确保ID设置正确
        boolean success = announcementService.updateAnnouncement(announcement);
        if (success) {
            return ResponseEntity.ok(announcementService.getAnnouncementById(id));
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除公告
     * @param id 公告ID
     * @return 无返回内容
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteAnnouncement(@PathVariable Long id) {
        boolean success = announcementService.deleteAnnouncement(id);
        if (success) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.notFound().build();
    }
}